package cn.tedu.goods.management.service.impl;


import cn.tedu.common.enumerator.ServiceCode;
import cn.tedu.common.ex.ServiceException;
import cn.tedu.common.pojo.authentication.CurrentPrincipal;
import cn.tedu.goods.management.dao.persist.repository.IGoodsRepository;
import cn.tedu.goods.management.pojo.eneity.Goods;
import cn.tedu.goods.management.pojo.param.GoodsAddNewParam;
import cn.tedu.goods.management.pojo.param.GoodsAvatarParam;
import cn.tedu.goods.management.pojo.param.GoodsUpdateParam;
import cn.tedu.goods.management.pojo.vo.GoodsListForUserVO;
import cn.tedu.goods.management.pojo.vo.GoodsListItemVO;
import cn.tedu.goods.management.service.IGoodsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class GoodsServiceImpl implements IGoodsService {
    @Autowired
    private IGoodsRepository goodsRepository;

    @Override
    public void deleteById(Long id) {
        int row = goodsRepository.delete(id);
        if (row!=1){
            String message = "删除失败,请稍后再试!";
            throw new ServiceException(ServiceCode.ERROR_DELETE,message);
        }
    }

    @Override
    public List<GoodsListItemVO> selectGoodsList() {
        return goodsRepository.selectGoodsList();
    }

    @Override
    public List<GoodsListForUserVO> selectGoodsListForUser() {
        return goodsRepository.selectGoodsListForUser();
    }

    @Override
    public void addNew(GoodsAddNewParam goodsAddNewParam) {
        Goods goods = new Goods();
        BeanUtils.copyProperties(goodsAddNewParam,goods);
        goods.setSalesCount(0);
        goods.setGmtModified(LocalDateTime.now());
        goodsRepository.insert(goods);
    }

    @Override
    public int updateById(GoodsUpdateParam goodsUpdateParam) {
        Goods goods = goodsRepository.selectById(goodsUpdateParam.getId());
        BeanUtils.copyProperties(goodsUpdateParam,goods);
        goods.setGmtModified(LocalDateTime.now());
        return goodsRepository.updateById(goods);
    }

    @Override
    public void avatar(String goodNames, GoodsAvatarParam goodsAvatarParam) {
        Goods goods=new Goods();
        BeanUtils.copyProperties(goodsAvatarParam,goods);
        goods.setGoodsName(goodNames);
        int rows = goodsRepository.avatar(goods);

        if (rows!=1){
            String message = "修改失败，服务器忙，请稍后再尝试！";
            throw new ServiceException(ServiceCode.ERROR_UPDATE, message);
        }
    }
}
